package com.yswee.framework.widget;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.yswee.framework.Application;
import com.yswee.framework.R;
import com.yswee.framework.utils.UnitUtils;

public class MToast {
	private static Toast mToast;

	public static void showToastMessage(int resId) {
		showToastMessage(resId, Toast.LENGTH_SHORT);
	}

	public static void showToastMessage(int resId, int duration) {
		showToastMessage(Application.get().getResources().getString(resId), duration);
	}

	public static void showToastMessage(String text) {
		showToastMessage(text, Toast.LENGTH_SHORT);
	}

	public static void showToastMessage(final String text, final int duration) {
		if(Looper.getMainLooper() == Looper.myLooper()) {
			showToastMessageInner(text, duration);
		} else {
			new Handler(Looper.getMainLooper()).post(new Runnable() {
				@Override
				public void run() {
					showToastMessageInner(text, duration);
				}
			});
		}
	}
	
	private static void showToastMessageInner(String text, int duration) {
		if(mToast == null) {
			Context context = Application.get();
			mToast = new Toast(context);
			mToast.setDuration(duration);
			mToast.setGravity(Gravity.BOTTOM, 0, UnitUtils.dip2pix(context, 100));
			View view = LayoutInflater.from(context).inflate(R.layout.widget_mtoast, null);
			TextView tvmessage = (TextView) view.findViewById(R.id.tvmessage);
			tvmessage.setText(text);
			mToast.setView(view);
		} else {
			((TextView) mToast.getView().findViewById(R.id.tvmessage)).setText(text);
			mToast.setDuration(duration);
		}
		mToast.show();
	}
	
}
